package com.yy.controller;

import com.yy.enums.ResponseEnum;
import com.yy.pojo.Article;
import com.yy.service.Impl.ArticleServiceImpl;
import com.yy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author young
 * @date 2022/8/17 13:56
 * @description: 控制层
 */
@RestController
@RequestMapping("/mongo")
public class ArticleController {
    @Autowired
    private ArticleServiceImpl articleService;

    /**
     * 根据title名查询文章
     * @param title
     * @return
     */
    @GetMapping("/list/{title}")
    public Article getList(@PathVariable("title")String title) {
       return articleService.findOne(title);
    }

    /**
     * 插入一条数据
     * @param article 文章对象
     * @return
     */
    @PostMapping("/insert")
    public R<Boolean> insertArticle(Article article){
        boolean b = articleService.insertArticle(article);
       
        return R.ok(b);
    }

    /**
     * 获取所有数据
     * @return
     */
    @GetMapping("/all")
    public List<Article> all(){
        return articleService.all();
    }

    /**
     * 更新文章标题
     * @param id 文章id
     * @param title 文章标题
     * @return
     */
    @PostMapping("/update")
    public R<Integer> updateArticle(@RequestParam(value="id",required=false) String id, @RequestParam(value="title",required=false) String title){
        int i = articleService.updateArticle(id, title);
        if (i>0){
            return R.ok(i);
        }else{
            return R.buildFailure(ResponseEnum.FAIL.getCode(), ResponseEnum.FAIL.getResultMessage());
        }
    }

    /**
     * 删除id对应的文章
     * @param id 文章id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R<Boolean> deleteArticle(@PathVariable String id){
        boolean b = articleService.removeArticle(id);
        return R.ok(b);
    }
}
